/**
 * 
 */
package vehicleLogic;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import constants.Constants;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import vehicleEntity.PurchasedVehicleDisplay;
import vehicleEntity.PurchasedVehicleEntity;
import vehicleService.PurchaseService;
import vehicleService.SetRateService;

/**
 * @author Sashiraj Dhanarajan
 *
 */
public class PurchseLogic {

	/**
	 * This method fetches all purchased vehicle details and puts in an observable list
	 * @return Returns all the purchased vehicle.
	 * @throws Exception 
	 * @pre  The values should be fetched from purchase service and available in the result set
	 * @post This will return the fetched values in an observable list 
	 */
	public ObservableList<PurchasedVehicleDisplay> fetchPurchasedVehiclesDetails() throws Exception{

		System.out.println("Inside Logic Class");
		PurchaseService ps = new PurchaseService();
		ResultSet rs = null;
		ObservableList<PurchasedVehicleDisplay> list = FXCollections.observableArrayList();
		try
		{
			rs = ps.fetchPurchasedVehiclesDetails();
			while(rs.next())
			{
				PurchasedVehicleDisplay pv = new PurchasedVehicleDisplay(rs.getInt("vehicleId"), rs.getDate("purchasedDate"),rs.getDate("manufDate"),
						rs.getDouble("vehicleIns"), rs.getDouble("amount"), rs.getString("VehicleName"), rs.getString("RegNo"),
						rs.getString("VIN"),rs.getString("vehicleClass"),rs.getString("vehicleType"));
				list.add(pv);
			}
		}

		catch(Exception e)
		{
			e.printStackTrace();
			ps.closeConnection();
			throw e;
		}
		ps.closeConnection();
		return list;
	}


	/**
	 * This method fetches the vehicle details based on the vehicleId entered
	 * @param VehicleId
	 * @return This returns the entity which contains the vehicle details
	 * @throws SQLException
	 * @pre The purchase service class is called and the vehicleId is entered
	 * @post The will fetch all vehicle details based on the vehicleId
	 */

	public PurchasedVehicleEntity fetchPurchasedVehicleDetail(int VehicleId) throws SQLException{
		System.out.println(VehicleId);

		PurchaseService purchaseservice = new PurchaseService();
		PurchasedVehicleEntity purchaseentity = null;
		ResultSet rs = null;
		try {
			rs = purchaseservice.fetchPurchasedVehicleDetail(VehicleId);
			purchaseentity = new PurchasedVehicleEntity();
			if(rs.next())
			{
				purchaseentity.setVehicleId(rs.getInt("vehicleId"));
				purchaseentity.setPurchasedDate(new Date(rs.getDate("purchasedDate").getTime()));
				purchaseentity.setManufDate(new Date(rs.getDate("manufDate").getTime()));
				purchaseentity.setVehicleIns(rs.getDouble("vehicleIns"));
				purchaseentity.setAmount(rs.getDouble("amount"));
				purchaseentity.setRegNo(rs.getString("RegNo"));
				purchaseentity.setVin(rs.getString("VIN"));
				purchaseentity.setVehicleType(rs.getString("vehicleType"));
				purchaseentity.setVehicleClass(rs.getString("vehicleClass"));
				purchaseentity.setVehicleName(rs.getString("VehicleName"));

				rs = purchaseservice.fetchVehicleSpec(VehicleId);
				while(rs.next()){
					String value = rs.getString("spec");
					if(value.equalsIgnoreCase(Constants.TRANSMISSION_AUTOMATIC) || value.equalsIgnoreCase(Constants.TRANSMISSION_MANUAL)){
						purchaseentity.setTransmission(value);
					}
					else{
						purchaseentity.setSpec(value);
					}
				}
				purchaseservice.closeConnection();
			}

			else{
				System.out.println("no value returned");
				purchaseentity=null;
			}	
		} catch (SQLException e) {
			purchaseservice.closeConnection();
			e.printStackTrace();
			throw e;
		} 
		purchaseservice.closeConnection();
		return purchaseentity;
	}

	/**
	 * This method saves the updated value of the purchased vehicle
	 * @param purchasedVehicle
	 * @return Returns Message whether edited details are updated are failed
	 * @throws SQLException 
	 * @pre The vehicle details should be fetched based on the vehicleId
	 * @post The edited values are saved into the database
	 */
	public String saveUpdatedValue(PurchasedVehicleEntity purchasedVehicle) throws SQLException {

		PurchaseService purchaseservice = new PurchaseService();

		try {
			System.out.println(purchasedVehicle.getVehicleType());
			System.out.println(purchasedVehicle.getVehicleId());
			purchaseservice.saveUpdatedValue(purchasedVehicle);
			purchaseservice.saveUpdatedValue2(purchasedVehicle);
			purchaseservice.saveUpdatedValue3(purchasedVehicle);
		
			purchaseservice.addVehicleSpecification(purchasedVehicle.getVehicleId(),purchasedVehicle.getSpec());
			purchaseservice.addVehicleSpecification(purchasedVehicle.getVehicleId(),purchasedVehicle.getTransmission());
			purchaseservice.transactionCommit();
			purchaseservice.closeConnection();
			return "Edit Values Updated Successfully";
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw e;
		}
	}

	/**
	 * This method adds new vehicle
	 * Returns vehicleID
	 * @param purchasedVehicle
	 * @return Returns the message whether vehicle is added successfully are adding vehicle failed
	 * @throws SQLException 
	 * @pre The purchase service is called and the add vehicle button is pressed and all the input fields should be given an entry
	 * @post Save the newly entered vehicle details into the database with the VehicleId
	 */
	public String addPurchasedVehicle(PurchasedVehicleEntity purchasedVehicle) throws SQLException{

		PurchaseService purchaseservice = new PurchaseService();
		ResultSet rs = null;
		try {
			rs = purchaseservice.addVehicle(purchasedVehicle);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
			purchaseservice.closeConnection();
			throw e2;
		}
		String message = "";
		try {
			if(rs != null && rs.next()){
				int vehicleId = rs.getInt("last_id");
				if(vehicleId != 0){
					purchasedVehicle.setVehicleId(vehicleId);
					purchaseservice.addPurchasedVehicle(purchasedVehicle);
					purchaseservice.addVehicleSpecification(vehicleId,purchasedVehicle.getSpec());
					purchaseservice.addVehicleSpecification(vehicleId,purchasedVehicle.getTransmission());
					purchaseservice.transactionCommit();
					message =  "vehicle successfully inserted with vehicleId " + vehicleId;
					System.out.println("vehicle successfully inserted"+vehicleId);
				}
				else{
					purchaseservice.transactionRollBack();
					message = "Adding vehicle failed";
				}
			}


		} catch (SQLException e) {
			// TODO Auto-generated catch block
			try {
				purchaseservice.transactionRollBack();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				purchaseservice.closeConnection();
				throw e1;
			}
			e.printStackTrace();
			purchaseservice.closeConnection();
			throw e;
		}

		purchaseservice.closeConnection();
		System.out.println(message);
		return message;
	}

	/**
	 * This method fetches vehicle type based on the vehicle class
	 * @param vehicleClass
	 * @return
	 * @throws SQLException
	 * @pre The vehicle class should be selected
	 * @post List the vehicle types
	 */
	public List<String> fetchVehicleType(String vehicleClass) throws SQLException {
		SetRateService service = new SetRateService();
		ResultSet rs = null;
		List<String> vehicleTypeList = new ArrayList<String>();
		try {
			rs = service.fetchVehicleType(vehicleClass);
			if(rs !=null){
				while(rs.next()){
					String type = rs.getString("vehicleType");
					vehicleTypeList.add(type);
				}
			}
		} catch (SQLException e) {
			service.closeConnection();
			e.printStackTrace();
			throw e;
		}
		service.closeConnection();
		return vehicleTypeList;
	}
	/**
	 * This method checks whether the VIN number is already exist
	 * @param vin
	 * @return
	 * @throws SQLException
	 * @pre Should not give the existing  VIN number
	 * @post Allows newly entered VIN number to be updated into database if it is unique
	 */

	public boolean checkVin(String vin) throws SQLException {
		PurchaseService service = new PurchaseService();
		ResultSet rs = null;
		try {
			System.out.println("checking vin");
			System.out.println("Vin :" + vin);
			rs = service.checkVIN(vin);
			if(rs.next()){
				System.out.println("Returning false");
				service.closeConnection();
				return false;
			}
			else{
				service.closeConnection();
				System.out.println("returning true");
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw e;
		}

	}
}
